package com.rxnetwork.sample.utils.interceptor;

import android.util.Log;

import com.rxnetwork.sample.utils.L;
import com.rxnetwork.sample.utils.network.JsonFormatUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 接口请求日志拦截打印
 */
public class AppLogInterceptor implements Interceptor {

    private static final String TAG = "RxNetWorkApiLog";
    private static final String CONTENT_TITLE = "Api Content-->:";
    private static final String HEADER_TITLE = "Api Header-->:";
    private static final String REQUEST_TITLE = "Api Request-->:";
    private static final String RESPONSE_TITLE = "Api Response-->:";

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(chain.request());
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        long t1 = System.nanoTime();
        L.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
        long t2 = System.nanoTime();
        L.i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        L.i(String.format("response body %s", JsonFormatUtil.format(content)));
        if (response.body() != null) {
            return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
        } else {
            return response;
        }
    }
}
